package com.zondy.mapgis.map.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.zondy.mapgis.android.map.dao.IBaseLayer;
import com.zondy.mapgis.core.attr.FieldType;
import com.zondy.mapgis.core.attr.Fields;
import com.zondy.mapgis.core.geodatabase.SFeatureCls;
import com.zondy.mapgis.core.geodatabase.XClsType;
import com.zondy.mapgis.core.map.DocumentItem;
import com.zondy.mapgis.core.map.GroupLayer;
import com.zondy.mapgis.core.map.MapLayer;
import com.zondy.mapgis.core.map.ServerLayer;
import com.zondy.mapgis.core.map.VectorLayer;
import com.zondy.mapgis.core.srs.SRefData;



/**
 * MapGIS版底图图层
 */
public class Layer implements IBaseLayer ,Serializable {

	private static final long serialVersionUID = 1L;
	private String alias = null;
	private MapLayer mapLayer = null;
	private boolean defSelect = false;
	private boolean isEditable = false;

	private ArrayList<IBaseLayer> childLayerList = new ArrayList<IBaseLayer>();
	private ArrayList<String> childLayerNameList = new ArrayList<String>();

	public Layer(MapLayer mapLayer) {
		if (mapLayer == null) {
			throw new IllegalArgumentException(
					"com.fjl.android.lib.core.mapLayer 构造器中的参数不能为 null");
		}
		this.mapLayer = mapLayer;
		initChild();
	}

	public void setChild(ArrayList<IBaseLayer> childLyrLst) {
		this.childLayerList = childLyrLst;
	}

	/**
	 * 是否组图层
	 * 
	 * @return
	 */
	@Override
	public boolean isGroupLayer() {
		if (mapLayer != null
				&& ((mapLayer instanceof GroupLayer) && !(mapLayer instanceof ServerLayer))) {
			return true;
		}
		return false;
	}

	/**
	 * 是否矢量图层
	 * 
	 * @return
	 */
	@Override
	public boolean isVectorLayer() {
		if (mapLayer != null && mapLayer instanceof VectorLayer) {
			return true;
		}
		return false;
	}

	public MapLayer getMapLayer() {

		return mapLayer;
	}

	/**
	 * 取图层名
	 * 
	 * @return
	 */
	@Override
	public String getName() {

		if (null != mapLayer) {
			return mapLayer.getName();
		}
		return null;
	}

	/**
	 * @return the alias
	 */
	@Override
	public String getAlias() {
		return alias;
	}

	/**
	 * @param alias
	 *            the alias to set
	 */
	@Override
	public void setAlias(String alias) {
		this.alias = alias;
	}

	/**
	 * 如果图层有别名则获取图层别名，否则获取图层名
	 * 
	 * @return
	 */
	@Override
	public String getAliasOrName() {
		if (alias == null || alias.length() == 0) {
			return getName();
		} else {
			return alias;
		}
	}

	@Override
	public boolean isDefSelect() {
		return defSelect;
	}

	@Override
	public void setDefSelect(boolean defSelect) {
		this.defSelect = defSelect;
	}

	@Override
	public DRect getRange() {
		if (mapLayer != null) {
			return new DRect(mapLayer.getRange());
		}
		return null;
	}

	/**
	 * 设置图层可见性，如果是组图层，会同时设置其子图层的可见性。如果是要将某一图层设为可见，将其所在GroupLayer设为可见。
	 * 
	 * @param visible
	 */
	@Override
	public void setVisible(boolean visible) {

		if (null == mapLayer) {
			return;
		}

		mapLayer.setVisible(visible);

		if (visible) {
			DocumentItem di = mapLayer.getParent();

			if (di != null && di instanceof GroupLayer) {
				((GroupLayer) di).setVisible(true);
			}
		}

		if (!(mapLayer instanceof GroupLayer)) {
			return;
		}
		GroupLayer groupLayer = ((GroupLayer) mapLayer);
		int count = groupLayer.getCount();
		for (int index = 0; index < count; index++) {

			MapLayer childLayer = groupLayer.item(index);
			childLayer.setVisible(visible);
		}

	}

	/**
	 * 图层是否可见
	 * 
	 * @return
	 */
	@Override
	public boolean isVisible() {

		if (null != mapLayer) {
			return mapLayer.getIsVisible();
		}
		return false;
	}

	@Override
	public boolean isEditable() {
		return isEditable;
	}

	@Override
	public void setEditable(boolean isEditable) {
		this.isEditable = isEditable;
	}

	/**
	 * 是否可以有透明度属性
	 * 
	 * @return
	 */
	@Override
	public boolean hasTransparency() {

		if (mapLayer == null) {
			return false;
		}
		if (mapLayer instanceof VectorLayer) {
			return true;
		}

		if (mapLayer instanceof GroupLayer) {

			List<IBaseLayer> layers = getChildLayers();
			for (IBaseLayer lyr : layers) {
				if (lyr.isVectorLayer()) {
					return true;
				}
			}
		}
		return false;
	}

	public void setSymbolShow(boolean bSymbolShow) {
		if (mapLayer instanceof VectorLayer) {
			((VectorLayer) mapLayer).setSymbolShow(bSymbolShow);
		}
	}

	/**
	 * 取图层透明度
	 * 
	 * @return 图层透明度（0-100，0表示不透明，100表示完全透明）， 如果图层为{@code null}或不是（矢量图层或组图层），返回
	 *         0. 如果图层为组图层，返回组图层中第一个矢量图层的透明度，如果组图层中没有矢量图层，返回 0.
	 */
	@Override
	public int getTransparency() {

		if (mapLayer == null || (!(mapLayer instanceof VectorLayer))
				&& (!(mapLayer instanceof GroupLayer))) {
			return 0;
		}
		int transparency = 0;

		if (mapLayer instanceof VectorLayer) {

			transparency = ((VectorLayer) mapLayer).getTransparency();
		} else if (mapLayer instanceof GroupLayer) {

			List<IBaseLayer> layers = getChildLayers();
			for (IBaseLayer lyr : layers) {
				if (lyr.isVectorLayer()) {
					transparency = lyr.getTransparency();
					break;
				}
			}
		}
		return transparency;
	}

	/**
	 * 设置图层透明度，如果是组图层，则设置所有子图层中矢量图层的透明度
	 * 
	 * @param transparency
	 *            图层透明度（0-100，0表示不透明，100表示完全透明）
	 * @return 如果图层为 {@code null} 或不是（矢量图层或组图层），则设置失败，返回 {@code false}，否则返回
	 *         {@code true}
	 */
	@Override
	public boolean setTransparency(int transparency) {

		if (transparency < 0 || transparency > 100) {
			System.out
					.println("Layer.setTransparency，失败，因为输入参数transparency不在合法范围内");
			return false;
		}

		if (mapLayer == null || (!(mapLayer instanceof VectorLayer))
				&& (!(mapLayer instanceof GroupLayer))) {
			return false;
		}
		boolean setted = false;

		if (mapLayer instanceof VectorLayer) {

			((VectorLayer) mapLayer).setTransparency((byte) transparency);
		} else if (mapLayer instanceof GroupLayer) {

			List<IBaseLayer> layers = getChildLayers();
			for (IBaseLayer lyr : layers) {

				if (lyr.isVectorLayer()) {
					lyr.setTransparency((byte) transparency);
					setted = true;
				}
			}
		}
		return setted;
	}

	/**
	 * 如果图层为组图层，就初始化，获取子图层
	 */
	private void initChild() {

		if (!isGroupLayer()) {
			return;
		}
		GroupLayer groupLayer = (GroupLayer) mapLayer;
		int layerCount = groupLayer.getCount();

		for (int i = 0; i < layerCount; i++) {

			MapLayer mapLayer = groupLayer.item(i);
			Layer layer = new Layer(mapLayer);
			childLayerList.add(layer);
			childLayerNameList.add(layer.getName());
		}
	}

	@Override
	public ArrayList<IBaseLayer> getChildLayers() {
		return childLayerList;
	}

	@Override
	public ArrayList<String> getChildLayerNames() {
		return childLayerNameList;
	}

	/**
	 * 获取组图层中具有给定名称的子图层
	 * 
	 * @param strName
	 * @return
	 */
	@Override
	public IBaseLayer getChildLayerByName(String strName) {
		if (!isGroupLayer()) {
			return null;
		}
		for (IBaseLayer lyr : childLayerList) {
			if (lyr.getName().equalsIgnoreCase(strName)) {
				return lyr;
			}
		}
		return null;
	}

	/**
	 * 将图层的所有字段名和字段类型存在输入参数中，输入参数应该是不为null的空队列
	 * 
	 * @param fldNames
	 * @param fldTyps
	 * @exception IllegalArgumentException
	 */
	@Override
	public int getFields(List<String> fldNames, List<LandFieldType> fldTyps) {

		if (fldNames == null || fldTyps == null) {
			throw new IllegalArgumentException(
					"Layer.getFields, 输入参数不正确。 fldNames == null || fldTypes == null");
		}
		if (mapLayer == null) {
			System.out.println("当前图层为空或者不是矢量图层，无法处理，直接返回");
			return 0;
		}
		if (!(mapLayer instanceof VectorLayer)) {
			return 1;
		}
		if (mapLayer.getData() == null) {
			return 2;
		}
		if (mapLayer.getData().getClsType() == XClsType.SFCls) {
			SFeatureCls cls = (SFeatureCls) mapLayer.getData();

			Fields fields = cls.getFields();
			int fieldCount = fields.getFieldCount();
			for (short ii = 0; ii < fieldCount; ii++) {

				String strName = fields.getField(ii).getFieldName();
				FieldType fldType = fields.getField(ii).getFieldType();
				fldNames.add(strName);
				fldTyps.add(LandFieldType.fromFieldType(fldType));
			}
			return 3;
		} else {
			System.out.println("当前图层不是简单要素类图层");
			return 4;
		}
	}

	/**
	 * 根据字段名取字段类型
	 * 
	 * @param strFldName
	 * @return
	 */
	public FieldType getFieldType(String strFldName) {

		if (mapLayer == null || !(mapLayer instanceof VectorLayer)) {
			System.out.println("当前图层为空或者不是矢量图层，无法处理，返回  null");
			return null;
		}
		if (strFldName == null || strFldName.length() == 0
				|| mapLayer.getData() == null) {
			System.out.println("字段名为空，返回  null");
			return null;
		}

		if (mapLayer.getData().getClsType() == XClsType.SFCls) {
			SFeatureCls cls = (SFeatureCls) mapLayer.getData();

			Fields fields = cls.getFields();
			int fieldCount = fields.getFieldCount();
			for (short ii = 0; ii < fieldCount; ii++) {

				String strName = fields.getField(ii).getFieldName();
				FieldType fldType = fields.getField(ii).getFieldType();
				if (strName.equalsIgnoreCase(strFldName)) {
					return fldType;
				}
			}
		} else {
			System.out.println("当前图层不是简单要素类图层");
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Layer [alias=" + alias + ", mapLayer=" + mapLayer
				+ ", defSelect=" + defSelect + ", isEditable=" + isEditable
				+ ", childLayerList=" + childLayerList
				+ ", childLayerNameList=" + childLayerNameList + "]";
	}

	@Override
	public double getMaxScale() {
		return mapLayer.getMaxScale();
	}

	@Override
	public double getMinScale() {
		return mapLayer.getMinScale();
	}

	@Override
	public SRefData getSpatialReference() {
		return mapLayer.getSrefInfo();
	}

	public IBaseLayer getLayerByName(String strName, boolean useAlias) {
		// TODO Auto-generated method stub
		return null;
	}
}
